package online.hxstart.code.concurrent.chapter03;

import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author huxing
 * @date 19-4-23 星期二 下午7:02
 * @describe
 */
public class ThreadJoin {
  public static void main(String[] args) throws InterruptedException {
    //
    List<Thread> threads = IntStream.range(1, 3).mapToObj(ThreadJoin::create).collect(toList());
    threads.forEach(Thread::start);
    for (Thread thread : threads) {
      System.out.println(thread.getName());
      thread.join();
    }
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread().getName() + "#" + i);
      shortSleep();
    }
  }

  private static Thread create(int index) {
    return new Thread(
        () -> {
          for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "#" + i);
            shortSleep();
          }
        },
        String.valueOf(index));
  }

  private static void shortSleep() {
    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
